﻿using System.Linq;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class FarmSolutionsLazyInitializer : BaseDomainListLazyInitializer<Farm, Solution>
    {
        protected override object InitializeTarget()
        {
            var spFarm = SPFarm.Local;

            return spFarm.Solutions
                .Select(s => CreateSolution(s))
                .ToVirtualList();
        }

        private Solution CreateSolution(SPSolution s)
        {
            var solution = new Solution
                {
                    Farm = Owner,
                    Id = s.SolutionId,
                    Name = s.Name,
                    DisplayName = s.DisplayName,
                    Deployed = s.Deployed,
                    DeploymentState = s.DeploymentState,
                    ContainsCasPolicy = s.ContainsCasPolicy,
                    ContainsGlobalAssembly = s.ContainsGlobalAssembly,
                    ContainsWebApplicationResource = s.ContainsWebApplicationResource,
                    LastOperationDetails = s.LastOperationDetails,
                    LastOperationEndTime = s.LastOperationEndTime,
                    LastOperationResult = s.LastOperationResult
                };

            solution.FeatureDefinitions = Data.CreateProxiedList<FeatureDefinition>(
                new SolutionFeatureDefinitionsLazyInitializer { Owner = solution }
                );

            solution.DeployedWebApplications = Data.CreateProxiedList<WebApplication>(
                new SolutionDeployedWebApplicationsLazyInitializer { Owner = solution }
                );

            return solution;
        }
    }
}
